import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../core/auth/user_manager.dart';
import '../../../core/auth/user_profile.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with SingleTickerProviderStateMixin {

  // 先不强制解包
  UserProfile? profile;
  late TextEditingController _nameController;
  late TextEditingController _emailController;
  late TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    profile = UserManager().profile;
    if (profile != null) {
      _nameController = TextEditingController(
          text: profile!.nickname ?? profile!.username ?? '');
      _emailController = TextEditingController(text: profile!.email ?? '');
      _phoneController = TextEditingController(text: profile!.phone ?? '');
    } else {
      // 可处理未登录情况
      _nameController = TextEditingController();
      _emailController = TextEditingController();
      _phoneController = TextEditingController();
    }
  }

  double _avatarScale = 1.0;

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final theme = Theme.of(context);
    final color = theme.colorScheme;

    return Scaffold(
      appBar: AppBar(title: Text(l10n.profileTitle)),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 头部信息卡片
            Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    // 左侧头像
                    GestureDetector(
                      onTapDown: (_) => setState(() => _avatarScale = 0.95),
                      onTapUp: (_) => setState(() => _avatarScale = 1.0),
                      onTapCancel: () => setState(() => _avatarScale = 1.0),
                      onTap: () {
                        // TODO: 头像选择逻辑
                      },
                      child: AnimatedScale(
                        scale: _avatarScale,
                        duration: const Duration(milliseconds: 150),
                        child: CircleAvatar(
                          radius: 40,
                          backgroundImage: const AssetImage(
                            'assets/images/avatar.jpg',
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),

                    // 右侧信息
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _nameController.text,
                            style: theme.textTheme.titleMedium!
                                .copyWith(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 6),
                          Text(
                            _nameController.text,
                            style: theme.textTheme.bodyMedium!
                                .copyWith(color: color.onSurfaceVariant),
                          ),
                          const SizedBox(height: 6),
                          Text(
                            _emailController.text,
                            style: theme.textTheme.bodyMedium!
                                .copyWith(color: color.onSurfaceVariant),
                          ),
                          const SizedBox(height: 6),
                          Text(
                            '',
                            style: theme.textTheme.bodySmall!
                                .copyWith(color: color.onSurfaceVariant),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 20.h),

            // 表单区域
            _buildFormSection(
              title: l10n.profileBasicInfo,
              children: [
                _buildTextField(
                  controller: _nameController,
                  label: l10n.profileNickname,
                  icon: Icons.person,
                ),
                _buildTextField(
                  controller: _emailController,
                  label: l10n.profileEmail,
                  icon: Icons.email,
                  keyboardType: TextInputType.emailAddress,
                ),
                _buildTextField(
                  controller: _phoneController,
                  label: l10n.profilePhone,
                  icon: Icons.phone,
                  keyboardType: TextInputType.phone,
                ),
              ],
            ),

            const SizedBox(height: 20),

            // 操作按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: () {
                  // TODO: 保存逻辑
                  ScaffoldMessenger.of(context)
                      .showSnackBar(SnackBar(content: Text(l10n.profileSaved)));
                },
                icon: const Icon(Icons.save),
                label: Text(l10n.commonSave),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFormSection({
    required String title,
    required List<Widget> children,
  }) {
    final theme = Theme.of(context);
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 1,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: theme.textTheme.titleMedium!
                  .copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            ...children
                .expand((widget) => [widget, const SizedBox(height: 12)])
                .toList()
              ..removeLast(),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    TextInputType keyboardType = TextInputType.text,
  }) {
    final theme = Theme.of(context);
    final color = theme.colorScheme;
    return TextField(
      controller: controller,
      keyboardType: keyboardType,
      decoration: InputDecoration(
        labelText: label,
        labelStyle:
            theme.textTheme.bodySmall!.copyWith(color: color.onSurfaceVariant),
        prefixIcon: Icon(icon, color: color.onSurfaceVariant),
        filled: true,
        fillColor: color.surfaceContainerHighest.withOpacity(0.3),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.symmetric(vertical: 14, horizontal: 0),
      ),
    );
  }
}
